using System;
using System.Collections.Generic;
using System.Text;
using SP.Parameter;

namespace SP.HwDeferredRS
{
    /// <summary>
    /// A simple base map feature
    /// </summary>
    public class NormalMapFusion : AbstractFusion
    {
        public NormalMapFusion()
        {
            AddPreprocessor(new Preprocessor("NORMALMAP_UV", 1, 3, 1, "UV channel (1-3) for normalMap."));
            AddPreprocessor(new Preprocessor("NORMALMAP_DXT5", 0, 1, 1, "Set to 1 to support DXT5 compressed normalMap."));

            // param normalMap
            AddParameter(
                new Texture2dParamter("normalMap", "normalMapSamp")
                .SetSRGBTexture(false)
                .SetUserData("fragment")
                );
        }

        public static string NAME = "NormalMap";
        public override string Name
        {
            get { return NAME; }
        }

        public override string Desc
        {
            get { return ""; }
        }

        public override Stage Stage
        {
            get { return Stage.Parallex; }
        }

        public override int UVChannelCount
        {
            get { return GetPreprocessor("NORMALMAP_UV").Value; }
        }

        public override void Code(StringBuilder b, string platform)
        {
            AddLine(b, "vec4 normalMap = tex2D(normalMapSamp, pipeline.Texcoord[NORMALMAP_UV-1]);");
            AddLine(b, "#if NORMALMAP_DXT5");
            AddLine(b, "vec3 normalTS = normalize(vec3(normalMap.wy * 2 - 1, 1));");
            AddLine(b, "#else // NORMALMAP_DXT5");
            AddLine(b, "vec3 normalTS = normalize(normalMap.xyz * 2 - 1);");
            AddLine(b, "#endif // NORMALMAP_DXT5");
            AddLine(b, "pipeline.Normal = normalize(normalTS.x * normalize(input.T_Vs) + normalTS.y * normalize(input.B_Vs) + normalTS.z * normalize(input.N_Vs));");
        }
    }
}
